public class Solution {
    public List<String> fullJustify(String[] words, int maxWidth) {

        if(maxWidth == 0) {
            return new ArrayList<>(Arrays.asList(words));
        }
        List<StringBuilder> list = new ArrayList<>();

        int i = 0;
        while(i < words.length) {
            int tempWidth = maxWidth;
            StringBuilder sb = new StringBuilder();
            while(i < words.length && words[i].length() <= tempWidth) {
                tempWidth -= (words[i].length() + 1);
                sb.append(words[i]).append(" ");
                i++;
            }
            sb = sb.deleteCharAt(sb.length() - 1);
            int or = sb.toString().split(" ").length - 1;
            int ed = maxWidth - sb.length();

            if(or != 0 && i != words.length) {
                int z = ed / or;
                int f = ed % or;
                StringBuilder tsb = new StringBuilder();
                for(int j = 0; j < z; j++) {
                    tsb = tsb.append(" ");
                }
                int ti = 0;
                for(int j = 0; j < f; j++) {
                    sb = sb.insert(sb.indexOf(" ", ti), tsb + " ");
                    ti = sb.indexOf(" ", ti) + z + 2;
                }
                for(int j = f; j < or; j++) {
                    sb = sb.insert(sb.indexOf(" ", ti), tsb);
                    ti = sb.indexOf(" ", ti) + z + 1;
                }
            } else {
                for(int j = 0; j < ed; j++) {
                    sb = sb.append(" ");
                }
            }
            list.add(sb);
        }
        return new ArrayList<>(list.stream().map(StringBuilder::toString).collect(Collectors.toList()));
    }
}